<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" destroyOnClose showFooter :title="getTitle" width="80%" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, computed } from 'vue';
import { BasicForm, useForm } from '@apps/antd-admin/src/components/Form/index';
import { BasicDrawer, useDrawerInner } from '@apps/antd-admin/src/components/drawer';
import { formSchema } from '../data/data';
import { Api } from '../data/api';
// 声明Emits
const emit = defineEmits(['success', 'register']);
//是否是编辑模式
const isUpdate = ref(true);
//计算标题
const getTitle = computed(() => (!isUpdate.value ? '新增商家' : '编辑商家'));
//配置表单
const [registerForm, { resetFields, setFieldsValue, updateSchema,validate, saveOrUpdate }] = useForm({
  rowKey: 'shopId',
  saveApi: Api.add,
  updateApi: Api.update,
  params:{
    shopCategoryId:1000
  },
  schemas: formSchema,
});
//表单赋值
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  setDrawerProps({ confirmLoading: false });
  await resetFields();
  isUpdate.value = !!data?.isUpdate;
  if (isUpdate.value) {
    await updateSchema({
      field: 'shopType',
      componentProps: {
        api: Api.listByParentId,
        immediate: true,
        labelField: 'typeName',
        valueField: 'typeId',
        showSearch: true,
        params: {
          parentId: data.record.shopGroup
        }
      },
    });
    await setFieldsValue(data.record);
  }
});

/**
 * 表单提交
 */
async function handleSubmit() {
  try {
    setDrawerProps({ confirmLoading: true });
    await saveOrUpdate(emit);
    closeDrawer();
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
